package com.soft.mainsite.component.spring;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.*;

import java.io.File;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Description:WebMvcConfiguration
 *
 * @author Jin
 * @create 2017-05-18
 **/
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Value("${enable.virtual.path}")
    String enableVirtualPath;

    @Value("${windows.file.upload.path}")
    String windowsUploadPath;

    @Value("${linux.file.upload.path}")
    String linuxUploadPath;


    @Value("${system.site.static.path}")
    String staticPath;


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String uploadPath =
                "true".equals(enableVirtualPath)
                        ?
                        (System.getProperty("os.name").toLowerCase().startsWith("win")
                                ?
                                "file:" + windowsUploadPath.replace("/", File.separator) + File.separator + "upload" + File.separator
                                :
                                "file:" + linuxUploadPath.replace("/", File.separator) + File.separator + "upload" + File.separator)
                        :
                        "classpath:static";
        registry.addResourceHandler("/upload/**").addResourceLocations(uploadPath);
        registry.addResourceHandler("/Uploads/**").addResourceLocations(uploadPath + "Uploads" + File.separator);
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/html/**").addResourceLocations("file:" + staticPath.replace("/", File.separator) + File.separator + "html" + File.separator);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins(CorsConfiguration.ALL)
                .allowedHeaders(CorsConfiguration.ALL)
                .allowCredentials(true)
                .allowedMethods(Stream.of(HttpMethod.values()).map(httpMethod -> httpMethod.name()).collect(Collectors.toList()).toArray(new String[]{}));
    }

}
